<template>
  <div class="home">
    <ul>
      <li
        v-for="item of msgList"
        :key="item.id"
      >
        <p>
          <span>{{ item.user }}</span>
          <span>{{ new Date(item.dateTime) }}</span>
        </p>
        <p>消息: {{ item.msg }} </p>
      </li>
    </ul>

    <input type="text" placeholder="请输入消息" v-model="msg" />
    <button @click="handleSendBtnClick">发送</button>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useWebSocket } from '../hooks';

export default {
  name: 'Home',
  setup() {
    const router = useRouter();
    const ws = useWebSocket(handleMessage);
    const state = reactive({
      msg: '',
      msgList: []
    });

    let username = '';

    onMounted(() => {
      username = localStorage.getItem('username');

      if (!username) {
        router.push('/login');
        return
      }
    })

    const handleSendBtnClick = () => {
      const _msg = state.msg.trim();

      if (!_msg.length) return;

      ws.send(JSON.stringify({
        id: Date.now(),
        user: username,
        dateTime: Date.now(),
        msg: _msg
      }));

      state.msg = '';
    }

    function handleMessage(e) {
      // console.log('FE: WebSocket messgae', e);
      const data = JSON.parse(e.data);
      
      state.msgList.push(data)
    }

    return {
      ...toRefs(state),
      handleSendBtnClick
    }
  }
}
</script>
